const Ticket = require('../models/ticket');
const Apply = require('../models/apply');

module.exports = function(body) {
    const processor = function(t) {
        return Apply.where({
            id: body.id
        })
        .fetch()
        .then(apply => {
            return Ticket.where({
                apply_id: apply.get('id')
            })
            .fetchAll()
            .then(tickets => {
                return tickets.models;
            })
            .map(ticket => {
                let dates = 0;
                body.dates.map(item => {
                    dates = dates | item.bit_id;
                });
                if(apply.get('type') === '备售') {
                    return ticket.save({
                        status: Ticket.READY,
                        apply_id: apply.get('id'),
                        price: body.price,
                        b_percent: body.b_percent,
                        customer_id: body.customer.id,
                        start_time: body.start_time,
                        end_time: body.end_time,
                        weekdays: body.weekdays,
                        days: body.days,
                        dates: dates,
                    }, {
                        transacting: t,
                        method: 'update'
                    });
                }
                return ticket.save({
                    status: Ticket.UNUSED,
                    apply_id: apply.get('id'),
                    price: body.price,
                    b_percent: body.b_percent,
                    customer_id: body.customer.id,
                    start_time: body.start_time,
                    end_time: body.end_time,
                    weekdays: body.weekdays,
                    dates: dates,
                }, {
                    transacting: t,
                    method: 'update'
                });
            })
            .then(() => {
                return apply.save({
                    status: 1,
                    price: body.price,
                    leader_id: body.leader_id,
                    pay_type: body.pay_type,
                    b_percent: body.b_percent,
                    remark: body.remark,
                    apply_no: body.apply_no
                }, {
                    transacting: t,
                    method: 'update'
                });
            });
        });
    };
    return Apply.buildTransaction(processor);
};
